﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Entity.Migrations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using com.nm;
using com.nm.ApiServer;
using com.nm.ApiServer.Attributes;
using com.nm.Attributes;
using com.nm.db.Models.Terminal;
using Senparc.Weixin.Helpers.Extensions;
using Senparc.Weixin.Work.AdvancedAPIs;
using Senparc.Weixin.Work.AdvancedAPIs.MailList;
using Senparc.Weixin.Work.Containers;
using Senparc.Weixin.Work.Helpers;
using WeiXinAPI.Common;
using WeiXinAPI.model;
using EntityFramework.Extensions;

namespace WeiXinAPI
{
    public class WxConditionConfigHandler: BaseHandler
    {
        #region 获取 GetWxCorpInfo
        
        [Description("获取报表参数配置")]
        [ReturnType(typeof(IList<ConditionConfigModel.ReportConfigModel>))]
        public ApiResult GetWxReportConfig(int reportId)
        {
            try
            {
                if (reportId <= 0)
                {
                    return Error("请求参数异常，请重新再试");
                }

                var dc = new TerminalEntities();
                var list = (from a in dc.wx_report_config
                            where a.report_id == reportId
                            select a).ToList().Select(a => new ConditionConfigModel.ReportConfigModel
                            {
                                config_id = a.config_id,
                                report_id = a.report_id,
                                config_sequence = a.config_sequence,
                                config_textdescription = a.config_textdescription,
                                config_controltype = a.config_controltype,
                                config_controlid = a.config_controlid,
                                config_source = a.config_source,
                                config_value = a.config_value,
                                config_cascade = a.config_cascade,
                                config_paramname = a.config_paramname
                            }).OrderBy(a => a.config_sequence).ToList();
                if (list != null && list.Count > 0)
                {
                    return Success(list);
                }
                else
                {
                    return Error("报表无参数条件配置");
                }
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
        }

        #endregion

        #region 获取报表列表 GetReportList

        [MustLogin]
        [Description("获取报表列表")]
        [ReturnType(typeof(IList<DepartmentListForJsTree>))]
        public ApiResult GetReportList([ParamDescription("企业微信的GUID")] string CIdentification = "", [ParamDescription("搜索的报表标题")] string conditionTitle = "")
        {
            var guid = Guid.Empty;
            if (!CIdentification.IsNullOrWhiteSpace())
            {
                if (!Guid.TryParse(CIdentification, out guid))
                {
                    return Error("参数异常");
                }
            }

            var dc = new TerminalEntities();
            if (!CIdentification.IsNullOrWhiteSpace() && !conditionTitle.IsNullOrWhiteSpace())
            {
                var list = new TerminalEntities().Report.Where(x => x.CIdentification == guid && x.Title.Contains(conditionTitle)).ToList();
                return Success(list);
            }
            else if (!CIdentification.IsNullOrWhiteSpace() && conditionTitle.IsNullOrWhiteSpace())
            {
                var list = new TerminalEntities().Report.Where(x => x.CIdentification == guid).ToList();
                return Success(list);
            }
            else if (CIdentification.IsNullOrWhiteSpace() && !conditionTitle.IsNullOrWhiteSpace())
            {
                var list = new TerminalEntities().Report.Where(x => x.Title.Contains(conditionTitle)).ToList();
                return Success(list);
            }
            else
            {
                var list = dc.Report.ToList();
                return Success(list);
            }
        }

        [MustLogin]
        [JsonType]
        [Description("保存报表参数列表")]
        [ReturnType(typeof(int), "0-成功")]
        public ApiResult SaveReportList([ParamDescription("保存报表参数")] ConditionConfigModel.ReportParameter param)
        {
            try
            {
                if (param == null)
                {
                    return Error("参数不能为空");
                }
                if (param.report_id == 0)
                {
                    return Error("报表ID不能为0");
                }
                if (param.list == null)
                {
                    return Error("参数列表不能为空");
                }
                var dc = new TerminalEntities();
                dc.wx_report_config.Where(a => a.report_id == param.report_id).Delete();

                foreach (var item in param.list)
                {
                    var data = new wx_report_config
                    {
                        report_id = item.report_id,
                        config_sequence = item.config_sequence,
                        config_textdescription = item.config_textdescription,
                        config_controltype = item.config_controltype,
                        config_controlid = item.config_controlid,
                        config_source = item.config_source,
                        config_value = item.config_value,
                        config_cascade = item.config_cascade,
                        config_paramname = item.config_paramname
                    };
                    dc.wx_report_config.Add(data);
                }
                dc.SaveChanges();

            }
            catch (Exception ex)
            {
                return Error(ex);
            }
            return Success(0);
        }

        [MustLogin]
        [Description("复制报表设置")]
        [ReturnType(typeof(int), "0-成功")]
        public ApiResult CopyReport([ParamDescription("源ID")] int SourceID, [ParamDescription("目标ID")] int TargetID)
        {
            var dc = new TerminalEntities();
            using (var tran = dc.Database.BeginTransaction())
            {
                try
                {
                    if (SourceID == 0 || TargetID == 0)
                    {
                        return Error("报表ID不能为0");
                    }
                    var del = dc.wx_report_config.Where(d => d.report_id == TargetID);
                    dc.wx_report_config.RemoveRange(del);
                    var query = dc.wx_report_config.Where(d => d.report_id == SourceID).ToList().Select(
                        d => new wx_report_config
                        {
                            report_id = TargetID,
                            config_sequence = d.config_sequence,
                            config_textdescription = d.config_textdescription,
                            config_controltype = d.config_controltype,
                            config_controlid = d.config_controlid,
                            config_source = d.config_source,
                            config_value = d.config_value,
                            config_cascade = d.config_cascade,
                            config_paramname = d.config_paramname
                        });
                    if (query.Any())
                    {
                        dc.wx_report_config.AddRange(query);
                    }
                    dc.SaveChanges();
                    tran.Commit();
                    return Success(0);
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    Log.Error(ex);
                    return Error("保存失败!");
                }
                finally
                {
                    tran.Dispose();
                }
            }
        }
        #endregion
    }
}
